package com.cq.hd.member.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cq.hd.common.response.Throw;
import com.cq.hd.member.api.dto.BusinessSubscribeDto;
import com.cq.hd.member.api.dto.BusinessSubscribeUpdateDto;
import com.cq.hd.member.api.vo.BusinessSubscribeCountVo;
import com.cq.hd.member.api.vo.BusinessSubscribeVo;
import com.cq.hd.member.mapper.TbBusinessMapper;
import com.cq.hd.member.po.TbBusinessPo;
import com.cq.hd.member.po.TbBusinessSubscribePo;
import com.cq.hd.member.mapper.TbBusinessSubscribeMapper;
import com.cq.hd.member.service.TbBusinessSubscribeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cq.hd.member.service.TbUserPointsAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.interceptor.DefaultTransactionAttribute;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 订阅商家表 服务实现类
 * </p>
 *
 * @author mYunYu
 * @since 2023-11-21
 */
@Service
public class TbBusinessSubscribeServiceImpl extends ServiceImpl<TbBusinessSubscribeMapper, TbBusinessSubscribePo> implements TbBusinessSubscribeService {

    @Autowired
    private TbBusinessMapper businessMapper;

    @Autowired
    private TbUserPointsAccountService userPointsAccountService;

    @Autowired
    private PlatformTransactionManager transactionManager;

    @Override
    public List<Long> listByUserId(Long userId) {
        List<TbBusinessSubscribePo> tbBusinessSubscribePos = baseMapper.selectList(new QueryWrapper<TbBusinessSubscribePo>().eq("del_state", 0)
                .eq("user_id", userId));
        if (!CollectionUtils.isEmpty(tbBusinessSubscribePos)) {
            return tbBusinessSubscribePos.stream().map(TbBusinessSubscribePo::getBusinessId).collect(Collectors.toList());
        }
        return null;
    }

    @Override
    public BigDecimal updateState(BusinessSubscribeUpdateDto businessSubscribeUpdateDto) {
        Long businessId = businessSubscribeUpdateDto.getBusinessId();
        Long userId = businessSubscribeUpdateDto.getUserId();
        // 订阅状态：1-订阅，2-取消订阅
        Integer subscribeState = businessSubscribeUpdateDto.getSubscribeState();
        BigDecimal points = BigDecimal.ZERO;

        TransactionStatus transaction = transactionManager.getTransaction(new DefaultTransactionAttribute());
        try {
            if (subscribeState == 1) {
                TbBusinessPo tbBusinessPo = businessMapper.selectById(businessId);
                if (tbBusinessPo == null || tbBusinessPo.getDelState() != 0) {
                    Throw.isBusinessException("未找到商家数据");
                }

                // 查询是否存在记录
                List<TbBusinessSubscribePo> tbBusinessSubscribePos = baseMapper.selectList(new QueryWrapper<TbBusinessSubscribePo>()
                        .eq("business_id", businessId)
                        .eq("user_id", userId));
                if (!CollectionUtils.isEmpty(tbBusinessSubscribePos)) {
                    TbBusinessSubscribePo tbBusinessSubscribePo = tbBusinessSubscribePos.get(0);
                    tbBusinessSubscribePo.setUpdateTime(LocalDateTime.now());
                    tbBusinessSubscribePo.setDelState(0);
                    baseMapper.updateById(tbBusinessSubscribePo);
                } else {
                    // 添加订阅记录
                    TbBusinessSubscribePo tbBusinessSubscribePo = new TbBusinessSubscribePo();
                    tbBusinessSubscribePo.setBusinessId(businessId);
                    tbBusinessSubscribePo.setUserId(userId);
                    tbBusinessSubscribePo.setCreateTime(LocalDateTime.now());
                    int insert = baseMapper.insert(tbBusinessSubscribePo);
                    if (insert == 0) {
                        Throw.isBusinessException("订阅失败");
                    }

                    // 发放订阅积分
                    points = userPointsAccountService.getSubscribePoints(businessId, userId);
                }
            } else if (subscribeState == 2) {
                baseMapper.update(null, Wrappers.<TbBusinessSubscribePo>lambdaUpdate()
                        .set(TbBusinessSubscribePo::getDelState, 1)
                        .eq(TbBusinessSubscribePo::getBusinessId, businessId)
                        .eq(TbBusinessSubscribePo::getUserId, userId)
                );

                // 扣减订阅获得的积分
                userPointsAccountService.returnSubscribePoints(businessId, userId);
            }

            transactionManager.commit(transaction);
        } catch (Exception e) {
            // 回滚事务
            transactionManager.rollback(transaction);
            Throw.isBusinessException(e.getMessage());
        }

        return points;
    }

    @Override
    public List<BusinessSubscribeVo> listByBusinessIds(List<Long> businessIds) {
        return baseMapper.listByBusinessIds(businessIds);
    }

    @Override
    public List<BusinessSubscribeVo> listByDto(BusinessSubscribeDto businessSubscribeDto) {
        return baseMapper.listByDto(businessSubscribeDto);
    }

    @Override
    public Map<Long, Integer> getBusinessSubscribeCount(List<Long> businessIds) {
        if (CollectionUtils.isEmpty(businessIds)) {
            return Collections.emptyMap();
        }
        List<BusinessSubscribeCountVo> businessSubscribeCountVos = baseMapper.statisticsBusinessSubscribeCount(businessIds);
        if (!CollectionUtils.isEmpty(businessSubscribeCountVos)) {
            return businessSubscribeCountVos.stream()
                    .collect(Collectors.toMap(BusinessSubscribeCountVo::getBusinessId, BusinessSubscribeCountVo::getNum));
        }
        return Collections.emptyMap();
    }
}
